<template>
  <div class="userinfo-dialog">
    <el-dialog v-model="dialogVisible" title="修改用户" width="600" destroy-on-close :close-on-click-modal="false"
      append-to-body>
      <el-form class="userInfoForm" ref="userInfoRef" :model="userInfoForm" :rules="userInfoRules" label-width="80">
        <el-form-item label="姓名" prop="nick_name">
          <el-input placeholder="请输入姓名" v-model.trim="userInfoForm.nick_name" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userInfoForm.gender">
            <el-radio :value="1">男</el-radio>
            <el-radio :value="0">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="userInfoForm.cla_id"  label="学号" prop="school_code">
          <el-input placeholder="请输入学号" v-model="userInfoForm.school_code" />
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input placeholder="请输入手机号" v-model.trim="userInfoForm.mobile" />
        </el-form-item>

        <el-form-item v-if="collegeArr.length >= 2" label="学院" prop="college_ids">
          <el-radio-group v-model="userInfoForm.college_ids">
            <el-radio v-for="item in collegeArr" :key="item.id" :label="item.id + ''">{{
              item.name
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="useUserStore().rolesName == '管理组'&&!userData.cla_id" label="选择组织" prop="arch_id">

          <el-select multiple v-model="userInfoForm.arch_id" placeholder="请选择组织" style="width: 300px">
            <el-option v-for="item in archList" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="userInfoForm.cla_id||userData.flag" label="选择班级" prop="cla_id">
          <el-select v-model="userInfoForm.cla_id" placeholder="请选择班级" style="width: 300px">
            <el-option v-for="item in claList" :label="item.cla_name" :value="item.id" />
          </el-select>
        </el-form-item>


      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button :disabled="isDisabled" @click="updateUser" type="primary"> 确定 </el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { adminTree } from "@/api/admin/schoolTree";
import { aviCollege } from "@/api/user";
import { upUserInfo, upArch } from "@/api/login";
import { ElMessage } from "element-plus";
import useUserStore from "@/store/modules/user";

import { classList } from "@/api/banji/classadmin"
const { proxy } = getCurrentInstance();
const props = defineProps({
  userData: {
    type: Object,
  }
});
const emits = defineEmits(["upUserSuccess", "upTemUserSuccess"]);
const dialogVisible = ref(false);
// 组织列表
const archList = ref([]);

// 是否禁用确定按钮,做防抖
const isDisabled = ref(false)
//班级列表
const claList = ref([]);
// 学院列表
const collegeArr = ref([]);

// 获取管理端树形结构
const getAdminTree = () => {
  adminTree().then((res) => {
    console.log(res);
    function transformData(res) {
      const archList = [];
      for (const item of res) {
        const collegeName = item.arch_list.find((i) => i.parent_id === "0").name;
        for (const archItem of item.arch_list) {
          if (!archItem.name.includes("学生组")&&archItem.name!=collegeName) {
            archList.push({
              id: archItem.id,
              name: `${collegeName}-${archItem.name}`,
              tenant_id: archItem.tenant_id,
            });
          }
        }
      }
      return archList;
    }
    const result = transformData(res);
    const filteredArr = result.filter(item => !item.name.includes("学生组"));
    console.log(filteredArr);
    archList.value = filteredArr
  })
}
const openDialog = async () => {
  dialogVisible.value = true;
  getClaList()
  // 确保在打开对话框时已经获取到了组织架构数据
  if (archList.value.length === 0) {
    try {
      await getAdminTree();
    } catch (error) {
      console.error('打开对话框时获取组织架构失败:', error);
    }
  }
}

// 获取班级列表
const getClaList = () => {
  if (useUserStore().rolesName == "老师组" && !useUserStore().is_super) {
    let options = {
      for_me: true,
      page_size: 100,
      page_num: 1,
    }
    classList(options).then(res => {
      claList.value = res.list
    })
  } else if (useUserStore().rolesName == "管理组" && !useUserStore().is_super) {

    let options = {
      for_me: false,
      page_size: 100,
      page_num: 1,
      tenant_id:useUserStore().tenant_id
    }
    classList(options).then(res => {
      claList.value = res.list
    })
  }else if(useUserStore().rolesName == "管理组" && useUserStore().is_super){
      let options = {
        for_me: false,
        page_size: 100,
        page_num: 1,
      }
      classList(options).then(res => {
        claList.value = res.list
      })

  }
}


const userInfoForm = ref({
  nick_name: "",
  gender: "",
  mobile: "",
  college_ids: "",
  arch_id: [],
  school_code: "",
  cla_id: [],
});

const userInfoRules = ref({
  nick_name: [{ required: true, message: "姓名不能为空", trigger: "blur" }, { min: 2, max: 15, message: '姓名长度在2到15位之间', trigger: 'blur' }],
  school_code: [{ required: true, message: "学号不能为空", trigger: "blur" }, { min: 0, max: 30, message: '学号不能超过30位', trigger: 'blur' }],

  mobile: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }],
});
// 获取支持的学院
const getCollege = () => {
  aviCollege().then((res) => {
    collegeArr.value = res;
  });
};
// 更新用户
const updateUser = () => {
  userInfoForm.value.school_code = userInfoForm.value.school_code ? userInfoForm.value.school_code + '' : ''
  proxy.$refs.userInfoRef.validate((valid) => {
    if (valid) {
      isDisabled.value = true
      let data = {
        user: {
          user_id: userInfoForm.value.user_id,
          mobile: userInfoForm.value.mobile,
          gender: userInfoForm.value.gender,
          user_name: userInfoForm.value.user_name,
          nick_name: userInfoForm.value.nick_name,
          arch_id: userInfoForm.value.arch_id ? userInfoForm.value.arch_id.map(id => Number(id)) : [],
          cla_id: userInfoForm.value.cla_id ? Array.of(userInfoForm.value.cla_id) : [],
          school_code: userInfoForm.value.school_code + "",
          // tenant_id:useUserStore().tenant_id

        }
      };

      upArch({
        cla_id: userInfoForm.value.cla_id ? Array.of(userInfoForm.value.cla_id) : [],
        arch_id: userInfoForm.value.arch_id.map(id => Number(id)) || [],
        user_id: userInfoForm.value.user_id,
      }).then((res) => {
        console.log(res);
      });

      console.log(data);


      upUserInfo(data).then((res) => {
        if (!res) {
          ElMessage.success("更新成功");
          isDisabled.value = false
          dialogVisible.value = false;
          if (props.userData.flag) {
            emits("upTemUserSuccess");
          } else {
            emits("upUserSuccess");
          }
        } else {
          ElMessage.error(res.response.data);
        }
      });
    }
  });
};

watch(
  () => props.userData,
  async (nv) => {
   console.log(nv);
   
    if (nv) {
      try {
        // 确保在设置表单数据前已经获取到了组织架构
        // if (archList.value.length === 0) {
        //   await getAdminTree();
        // }
        userInfoForm.value = { ...nv };
        console.log(userInfoForm.value);
        userInfoForm.value.arch_id = userInfoForm.value.arch_id.map(item => String(item));
        // 处理college_ids的回显
        if (nv.college_ids) {
          userInfoForm.value.college_ids = nv.college_ids;
        }
      } catch (error) {
        console.error('设置用户数据失败:', error);
      }
    }
  },
  {
    deep: true,
    immediate: true
  }
);


getCollege();
defineExpose({
  openDialog
})


</script>

<style lang="scss" scoped>
.userInfoForm {
  padding-top: 30px;

  .phoneOut {
    display: flex;
    width: 100%;
    position: relative;

    .replace {
      position: absolute;
      right: 0;
      top: 0;
    }
  }
}

.dialog-footer {
  margin-top: 50px;
}
</style>